<template>
  <div>
    <div v-if="!readonly" style="text-align: right; margin-bottom: 4px;">
      <el-button-group style="margin-top: 0px; margin-right: 12px;">
        <!--        <el-tooltip :open-delay="500" content="历史记录" placement="top">-->
        <!--          <el-button :disabled="element.id===undefined" icon="el-icon-link" size="mini" type="info" @click="handleHistory" />-->
        <!--        </el-tooltip>-->
        <el-tooltip content="模版" placement="top" :open-delay="500">
          <el-button type="primary" icon-class="skill" size="mini" icon="el-icon-chat-line-square" style="height: 29px;" @click="handleTemplate" />
        </el-tooltip>
        <el-tooltip content="保存" placement="top" :open-delay="500">
          <el-button type="primary" icon-class="skill" size="mini" @click="saveTestCase(false)"><svg-icon icon-class="save" /></el-button>
        </el-tooltip>
      </el-button-group>
    </div>
    <el-card shadow="hover">
      <el-form ref="element" size="small" class="demo-table-expand" :rules="rules" label-width="100px" label-position="right" :model="element" :disabled="readonly">
        <el-form-item label="脚本类型" prop="scriptType">
          <el-select v-model="element.scriptType" placeholder="请选择脚本类型" size="mini" style="margin-right: 10px;" @change="changeScriptType">
            <el-option v-for="item in scriptTypeOptions" :key="item.value" :label="item.name" :value="item.value" :disabled="item.disabled" />
          </el-select>
        </el-form-item>
        <el-row :gutter="5">
          <el-form-item label="用例名称" prop="name">
            <el-col :span="17">
              <el-input v-model="element.name" placeholder="请输入用例名称" />
            </el-col>
            <el-col :span="4">
              <el-tooltip :open-delay="500" content="用例编写状态" placement="top">
                <el-select v-model="element.editStatus" placeholder="请选择用例编写状态" style="width: 100%">
                  <el-option v-for="item in editStatusOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-tooltip>
            </el-col>
            <el-col :span="3">
              <el-tooltip :open-delay="500" content="优先级" placement="top">
                <el-select v-model="element.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option v-for="item in priorityOptions" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-tooltip>
            </el-col>
          </el-form-item>
        </el-row>
        <div>
          <label style="font-size: 14px; color: #606266;">测试脚本</label>
          <div class="json-editor" style="border:solid 1px #dfe4ed;">
            <json-editor ref="scriptEditor" v-model="element.content" mode="python" />
          </div>
        </div>
      </el-form>
    </el-card>

    <el-dialog :visible.sync="templateDialogFormVisible" title="模版" width="500px" :close-on-click-modal="false">
      <el-alert close-text="Get!" style="margin-bottom: 10px" type="info">
        <div>1、为了让不熟悉 Locust 的用户方便使用，特提供了模版功能；</div>
        <div>2、每个模版都对应一个性能测试脚本；</div>
        <div>3、选择模版后会将脚本内容填到测试脚本中。</div>
      </el-alert>
      <el-select v-model="templateValue" placeholder="请选择模版" size="mini" style="margin-right: 10px; width: 100%;" @change="changeTemplate">
        <el-option v-for="item in templateOptions" :key="item.value" :label="item.name" :value="item.value" :disabled="item.disabled" />
      </el-select>
    </el-dialog>

    <!--    <el-dialog :visible.sync="historyDialogFormVisible" title="历史记录" width="1200px" :close-on-click-modal="false">-->
    <!--      <test-case-history-component-->
    <!--        ref="testCaseHistoryComponent"-->
    <!--        @dblclickResultRow="dblclickResultRow"-->
    <!--      />-->
    <!--    </el-dialog>-->
  </div>
</template>

<style lang="scss">
  .item {
    .el-input__inner {
      border: 1px solid #fff !important;
      resize: none;
    }
    .el-textarea__inner {
      border: 1px solid #fff !important;
      resize: none;
    }
  }
</style>

<script>
import { selectById as testScriptSelectById, create as testScriptCreate, update as testScriptUpdate } from '@/api/performance_test/test_script.js'
// import TestCaseHistoryComponent from '@/components/functional_test/History/testCaseHistory'
import { editStatusOptions, getEditStatusValue } from '@/enum/editStatus.js'
import { priorityOptions, getPriorityValue } from '@/enum/priority.js'
import { scriptTypeOptions, getScriptTypeValue, getScriptTypeName } from '@/enum/scriptType.js'
import { getCatalogTypeValue } from '@/enum/catalogType'
import JsonEditor from '@/components/JsonEditor'

export default {
  // components: { TestCaseHistoryComponent },
  components: { JsonEditor },
  props: {
    value: {
      type: Object,
      default() {
        return {
          catalogId: 0, // 分类 id
          textMode: false // 文本模式编辑
        }
      }
    },
    // 是否只读
    readonly: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      editStatusOptions, // 编写状态 options
      priorityOptions, // 优先级 options
      scriptTypeOptions, // 性能测试脚本类型 枚举类
      element: {}, // element 对象
      templateDialogFormVisible: false, // 模版 弹窗
      historyDialogFormVisible: false, // 历史记录弹窗
      locustDefault: '#coding=utf-8\n' +
        'import urllib3\n' +
        'import json\n' +
        'from locust import HttpUser, between, task\n' +
        '\n' +
        '# http 调试信息\n' +
        '# import logging\n' +
        '# from http.client import HTTPConnection\n' +
        '\n' +
        '# HTTPConnection.debuglevel = 1\n' +
        '# logging.basicConfig()\n' +
        '# logging.getLogger().setLevel(logging.DEBUG)\n' +
        '# requests_log = logging.getLogger("requests.packages.urllib3")\n' +
        '# requests_log.setLevel(logging.DEBUG)\n' +
        '# requests_log.propagate = True\n',
      jmeterDefault: '',
      loadrunnerDefault: '',
      templateOptions: [ // 模版 Options
        {
          value: 1,
          name: '单接口 - GET',
          disabled: false
        }, {
          value: 2,
          name: '单接口 - POST',
          disabled: false
        }, {
          value: 3,
          name: '多接口 - 接口间参数化',
          disabled: false
        }
      ],
      templateValue: '', // 模版 value
      rules: {
        scriptType: [
          { required: true, message: '必须选择一个脚本类型', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '测试用例名称不能为空', trigger: 'blur' },
          { max: 255, message: '测试用例名称长度不能超过 255 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    // 新增时初始化 element 数据
    resetElement() {
      this.element = {
        projectId: this.$store.getters.projectId,
        catalogId: this.value.catalogId,
        type: getCatalogTypeValue('性能测试用例'),
        scriptType: getScriptTypeValue('Locust'),
        editStatus: getEditStatusValue('编写中'),
        priority: getPriorityValue('P2'),
        name: '',
        content: ''
      }
    },
    // 设置 element 数据（当服务端返回数据后有些类型不符需要在这个方法中转换）
    setElement(ele) {
      this.element = ele
    },
    // 装载数据
    loadData(id) {
      testScriptSelectById(id).then(response => {
        this.setElement(response.data)

        if (getScriptTypeName(response.data.scriptType) === 'Locust') {
          this.$refs.scriptEditor.setMode('python')
        } else if (getScriptTypeName(response.data.scriptType) === 'JMeter') {
          this.$refs.scriptEditor.setMode('java')
        } else if (getScriptTypeName(response.data.scriptType) === 'LoadRunner') {
          this.$refs.scriptEditor.setMode('c')
        }
        this.$refs.scriptEditor.setValue(response.data.content)
      })
    },
    // 点击新增用例按钮时调用此方法
    add() {
      this.resetElement()
      this.changeScriptType(getScriptTypeValue('Locust'))
    },
    /**
     * 保存 测试用例
     * @param saveAndContinue 保存继续时，要传入 tree
     */
    saveTestCase(saveAndContinue) {
      this.$refs['element'].validate((valid) => {
        if (valid) {
          if (!this.element.id || this.element.id === 0) { // id = 0，新增
            if (!this.element.catalogId) { // 跟目录设置 parentId = 0
              this.element.catalogId = 0
            }
            testScriptCreate(this.element).then((response) => {
              this.element = response.data
              this.$emit('create', response.data)
              this.$message({ message: '添加成功!', type: 'success' })
            })
          } else { // 否则修改
            testScriptUpdate(this.element).then((response) => {
              this.$emit('update', response.data)
              this.$message({ message: '修改成功!', type: 'success' })
            })
          }
        }
      })
    },
    // 切换脚本类型
    changeScriptType(value) {
      if (getScriptTypeName(value) === 'Locust') {
        this.$refs.scriptEditor.setMode('python')
        this.$refs.scriptEditor.setValue(this.locustDefault)
      } else if (getScriptTypeName(value) === 'JMeter') {
        this.$refs.scriptEditor.setMode('java')
        this.$refs.scriptEditor.setValue(this.jmeterDefault)
      } else if (getScriptTypeName(value) === 'LoadRunner') {
        this.$refs.scriptEditor.setMode('c')
        this.$refs.scriptEditor.setValue(this.loadrunnerDefault)
      }
    },
    // 点击 模版 按钮
    handleTemplate() {
      this.templateDialogFormVisible = true
      this.templateValue = ''
    },
    // 改变 性能测试脚本模版
    changeTemplate(event) {
      if (event === 1) { // 单接口 - GET
        this.element.content = '#coding=utf-8\n' +
          'import urllib3\n' +
          'import json\n' +
          'from locust import HttpUser, between, task\n' +
          '\n' +
          'class AdminUser(HttpUser):\n' +
          '    urllib3.disable_warnings() # 关闭 http 警告\n' +
          '    wait_time = between(1, 2)\n' +
          '    host = \'https://qa.baijiayun.com:7171\'\n' +
          '\n' +
          '    @task\n' +
          '    def task_1(self):\n' +
          '        # 定义 url 请求参数\n' +
          '        url_query_data = {\n' +
          '            \'account\' : \'aa\',\n' +
          '            \'code\' : \'xxxxxx\'\n' +
          '        }\n' +
          '        # 定义 body 请求参数\n' +
          '        body_query_data = {\n' +
          '            \'body_id\' : 1,\n' +
          '            \'body_name\' : \'xx\'\n' +
          '        }\n' +
          '        # GET 请求，即有 url 参数，又有 body 参数\n' +
          '        with self.client.get("/user/user/login", params=url_query_data, json=body_query_data, catch_response=True, name="/user/user/login?account=[account]&code=[code]", verify=False) as response:\n' +
          '            # 返回 code 不为 0 报错\n' +
          '            if json.loads(response.text)[\'code\'] != 0:\n' +
          '                response.failure(\'/user/user/login 失败，返回 code != 0\')'
      } else if (event === 2) { // 单接口 - POST
        this.element.content = '#coding=utf-8\n' +
          'import urllib3\n' +
          'import json\n' +
          'from locust import HttpUser, between, task\n' +
          '\n' +
          'class AdminUser(HttpUser):\n' +
          '    urllib3.disable_warnings() # 关闭 http 警告\n' +
          '    wait_time = between(1, 2)\n' +
          '    host = \'https://qa.baijiayun.com:7171\'\n' +
          '\n' +
          '    @task\n' +
          '    def task_1(self):\n' +
          '        # 定义 url 请求参数\n' +
          '        url_query_data = {\n' +
          '            \'body_id\' : 1,\n' +
          '            \'body_name\' : \'xx\'\n' +
          '        }\n' +
          '        # 定义 body 请求参数\n' +
          '        body_query_data = {\n' +
          '            \'account\' : \'aa\',\n' +
          '            \'code\' : \'xxxxxx\'\n' +
          '        }\n' +
          '        # POST 请求，即有 url 参数，又有 body 参数\n' +
          '        with self.client.post("/user/user/login", params=url_query_data, json=body_query_data, catch_response=True, name="/user/user/login", verify=False) as response:\n' +
          '            # 返回 code 不为 0 报错\n' +
          '            if json.loads(response.text)[\'code\'] != 0:\n' +
          '                response.failure(\'/user/user/login 失败，返回 code != 0\')'
      } else if (event === 3) { // 多接口 - 接口间参数化
        this.element.content = '#coding=utf-8\n' +
          'import urllib3\n' +
          'import json\n' +
          'from locust import HttpUser, between, task\n' +
          '\n' +
          '# http 调试信息\n' +
          '# import logging\n' +
          '# from http.client import HTTPConnection\n' +
          '\n' +
          '# HTTPConnection.debuglevel = 1\n' +
          '# logging.basicConfig()\n' +
          '# logging.getLogger().setLevel(logging.DEBUG)\n' +
          '# requests_log = logging.getLogger("requests.packages.urllib3")\n' +
          '# requests_log.setLevel(logging.DEBUG)\n' +
          '# requests_log.propagate = True\n' +
          'class AdminUser(HttpUser):\n' +
          '    urllib3.disable_warnings() # 关闭 http 警告\n' +
          '    wait_time = between(1, 2)\n' +
          '    host = \'https://qa.baijiayun.com:7171\'\n' +
          '\n' +
          '    def on_start(self):\n' +
          '        # 定义 body 请求参数\n' +
          '        body_query_data = {\n' +
          '            \'account\' : \'lrs\',\n' +
          '            \'code\' : \'111111\'\n' +
          '        }\n' +
          '        # 登录并拿到 token\n' +
          '        with self.client.post("/user/user/login", json=body_query_data, catch_response=True, verify=False) as response:\n' +
          '            # 返回 code 不为 0 报错\n' +
          '            if json.loads(response.text)[\'code\'] == 0:\n' +
          '                res_token = json.loads(response.text)["data"]["token"]\n' +
          '                header = {\n' +
          '                    \'Token\' : res_token\n' +
          '                }                \n' +
          '                self.client.headers.update(header)\n' +
          '            else:\n' +
          '                response.failure(\'/user/user/login 失败，返回 code != 0\')\n' +
          '\n' +
          '    @task\n' +
          '    def task_1(self):\n' +
          '        with self.client.get("/user/user/getInfo", catch_response=True, verify=False) as response:\n' +
          '            if json.loads(response.text)[\'code\'] != 0:\n' +
          '                response.failure(\'/user/user/getInfo 失败，返回 code != 0\')'
      }
      this.$refs.scriptEditor.setValue(this.element.content)
      this.templateDialogFormVisible = false
    }
    // // 点击 history 按钮
    // handleHistory() {
    //   this.historyDialogFormVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.testCaseHistoryComponent.loadData(this.element.id)
    //   })
    // },
    // // 双击历史结果行
    // dblclickResultRow(ele) {
    //   this.historyDialogFormVisible = false
    //   this.setElement(ele)
    // }
  }
}
</script>
